package 多线程.三个线程实现顺序打印;

/**
 * 方式二：synchronized + wait + notify
 */
public class Test2 {
    //锁住的对象
    private final static Object lock = new Object();
    //A是否已经执行过
    private static boolean aExecuted = false;
    //B是否已经执行过
    private static boolean bExecuted = false;
    public static void main(String[] args) {
        Test2 t = new Test2();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                t.printA();
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }

    public static void printA() {
        synchronized (lock) {
            System.out.println("A");
            aExecuted = true;
            //唤醒所有等待线程
            lock.notifyAll();
        }
    }

    public static void printB() throws InterruptedException {
        synchronized (lock) {
            //获取到锁，但是要等A执行
            while (!aExecuted) {
                lock.wait();
            }
            System.out.println("B");
            bExecuted = true;
            lock.notifyAll();
        }
    }

    public static void printC() throws InterruptedException {
        synchronized (lock) {
            //获取到锁，但是要等B执行
            while (!bExecuted) {
                lock.wait();
            }
            System.out.println("C");
        }
    }
}